package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: YHL
 * @time: 2021/2/23 20:35
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService paramService;

    @Override
    public List<SpecGroupDTO> listSpecGroupByCategory(Long cid) {
        //select * from tb_spec_group where category_id = #{cid}
        return SpecGroupDTO.convertEntityList(this.query().eq("category_id",cid).list());
    }

    @Override
    public List<SpecGroupDTO> listSpecByCategory(Long cid) {
        List<SpecGroupDTO> specGroupDTOS = this.listSpecGroupByCategory(cid);
        //select * from tb_spec_param where category_id = #{cid}
        List<SpecParamDTO> specParamDTOS = SpecParamDTO.convertEntityList(
                this.paramService.query().eq("category_id", cid).list());
        //根据规格参数组id进行分组，map的key就是对应的规格参数组id，value是list集合，集合中存放的是groupId相同的所有的内容集合
        Map<Long, List<SpecParamDTO>> listMap = specParamDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        specGroupDTOS.forEach(specGroupDTO -> specGroupDTO.setParams(listMap.get(specGroupDTO.getId())));

        return specGroupDTOS;
    }
}
